package database;

import java.net.UnknownHostException;
import java.util.ArrayList;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;

public class DatabaseOperations implements IDatabaseOperations{

	private MongoClient mongoClient;
	private DB db;
	private DBObject jobsMap;
	private Gson gson;
	int id = 0;
	private DBCollection dbCollection;
	private DBObject record;

	public DatabaseOperations(){
		try {
			mongoClient = new MongoClient( "localhost" , 27017 );
			db = mongoClient.getDB( "RoadRunner" );
			dbCollection = db.getCollection("JOBS");          
			gson = new Gson();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void addJob(Job job) {
		jobsMap = new BasicDBObject();
		jobsMap.put(CollectionKey.ORDER_ID.toString(), job.getOrderId());
		jobsMap.put(CollectionKey.EXP_NAME.toString(), job.getExpName());
		jobsMap.put(CollectionKey.EXP_ADDRESS.toString(), job.getExpAdress());
		jobsMap.put(CollectionKey.DEST_NAME.toString(), job.getDestName());
		jobsMap.put(CollectionKey.DEST_ADDRESS.toString(), job.getDestAdress());
		jobsMap.put(CollectionKey.TRANSPORTER_NAME.toString(), job.getTransporterName());
		jobsMap.put(CollectionKey.JOB_STATE.toString(), job.getJobState().toString());
		dbCollection.save(jobsMap);
		
		//		String json = gson.toJson(job); 
//		System.out.println(json);
//		BasicDBObject basicDBObject = new BasicDBObject(Integer.toString(id), json );          
//		dbCollection.save(basicDBObject);
//		id++;
	}

	@Override
	public String getJob(int orderId) {
		
		String result = "";
		BasicDBObject query = new BasicDBObject(CollectionKey.ORDER_ID.toString(), orderId);

		DBCursor cursor = dbCollection.find(query);
		
		try {
		   while(cursor.hasNext()) {
		       record = cursor.next();
		       record.removeField("_id");
		       result = record.toString();
		       System.out.println(result);
		       
		   }
		} finally {
		   cursor.close();
		}
		
		return result;
	}
	
	@Override
	public ArrayList<String> getAllJobs() {
		ArrayList<String> results = new ArrayList<String>();
		DBCursor cursor = dbCollection.find();
		
		try {
		   while(cursor.hasNext()) {
		       record = cursor.next();
		       
		       record.removeField("_id");
		       results.add(record.toString());
		       
		   }
		} finally {
		   cursor.close();
		}
		
		for(String s: results){
			System.out.println(s);
		}
		
		return results;
	}
	
	
	
}
